
package com.droidathletics.boundary;

import java.util.ArrayList;

import javax.net.ssl.ManagerFactoryParameters;

import com.droidathletics.R;
import com.droidathletics.boundary.competition.ChronometerActivity;
import com.droidathletics.boundary.competition.CreateCompetition;
import com.droidathletics.boundary.competition.EditCompetition;
import com.droidathletics.boundary.competition.ImageAdapterCompetition;
import com.droidathletics.boundary.macrocycles.CreateMacrocycle;
import com.droidathletics.boundary.macrocycles.EditMacrocycle;
import com.droidathletics.boundary.macrocycles.ImageAdapterMacrocycle;
import com.droidathletics.boundary.microcycles.ImageAdapterListMicrocycles;
import com.droidathletics.boundary.microcycles.ListMicrocycles;
import com.droidathletics.boundary.sportsman.CreateSportsman;
import com.droidathletics.boundary.sportsman.EditSportsman;
import com.droidathletics.boundary.sportsman.ImageAdapterSportsman;
import com.droidathletics.control.ManageCompetition;
import com.droidathletics.control.ManageMacrocycle;
import com.droidathletics.control.ManageMicrocycle;
import com.droidathletics.control.ManageSportsman;
import com.droidathletics.control.ManageTrainer;
import com.droidathletics.entity.Competition;
import com.droidathletics.entity.Macrocycle;
import com.droidathletics.entity.Sportsman;

import android.widget.TabHost.TabContentFactory;
import android.app.AlertDialog;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.Toast;

public class MainMenu extends TabActivity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        instance = this;       
        
        manageSportsman = new ManageSportsman(this);
        manageCompetition = new ManageCompetition(this);
        manageMacrocycle = new ManageMacrocycle(this);
        manageMicrocycle = new ManageMicrocycle(this);
        
        watcher = new TextWatcher(){        	
            public void afterTextChanged(Editable s) { 
        		search();
        	}
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {}
        };
        
        search = (EditText) findViewById(R.id.fieldSearch);
		actualSearch = search.toString();
		search.addTextChangedListener(watcher);
        
        createClases.add(CreateSportsman.class);
        createClases.add(CreateMacrocycle.class);
        createClases.add(CreateCompetition.class);
        editClasses.add(EditSportsman.class);
        editClasses.add(EditMacrocycle.class);
        editClasses.add(EditCompetition.class);
        
        res = getResources();
        tabHost = getTabHost(); 
        //-----------------------------------------------------------------------------------------
        setSportsmanList();        
        tabHost.addTab(tabHost.newTabSpec("Sportsmen").setIndicator("Sportsmen",
                res.getDrawable(R.drawable.icon_createsportsman)).setContent(new TabContentFactory() {
        	            public View createTabContent(String arg0) {            	
        	                return listSportsman;
        	            }
        	        }));
        //----------------------------------------------------------------------------------------
        setMacrocycleslist();
        tabHost.addTab(tabHost.newTabSpec("Macrocycles").setIndicator("Macrocycles",
                res.getDrawable(R.drawable.icon_createsportsman)).setContent(new TabContentFactory() {
        	            public View createTabContent(String arg0) {            	
        	                return listMacrocycles;
        	            }
        	        }));
        //----------------------------------------------------------------------------------------
        setCompetitionList();
        tabHost.addTab(tabHost.newTabSpec("Competitions").setIndicator("Competitions",
                res.getDrawable(R.drawable.icon_createsportsman)).setContent(new TabContentFactory() {
        	            public View createTabContent(String arg0) {
        	                return listCompetition;
        	            }
        	        }));
        //----------------------------------------------------------------------------------------
        tabHost.setCurrentTab(2);
        tabHost.setCurrentTab(1);
        tabHost.setCurrentTab(0);
        tabHost.setCurrentTab(currentTab);
    }
    
    private void setSportsmanList(){   
        listSportsman = (ListView) findViewById(R.id.listSportsman);
 		adapterSportsman= new ImageAdapterSportsman(this, manageSportsman.readAllSportsman());
 		listSportsman.setAdapter(adapterSportsman);
 		listSportsman.setOnItemClickListener(new OnItemClickListener() {
 		    public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
 		    	final Sportsman itemSportsman = (Sportsman) listSportsman.getAdapter().getItem(position);
				if(itemSportsman != null) {
 		            AlertDialog.Builder builder = new AlertDialog.Builder(instance);
 		            builder.setTitle("Pick an Option");
 		            builder.setItems(popupItems, new DialogInterface.OnClickListener() {
 		                public void onClick(DialogInterface dialog, int item) {
 		                	switch(item){
	 		                	case 0:
	 		                		manageSportsman.deleteSportsman(itemSportsman.getName(),itemSportsman.getLastName());
	 		                		adapterSportsman= new ImageAdapterSportsman(instance, manageSportsman.readAllSportsman());
	 		                		listSportsman.setAdapter(adapterSportsman);
	 		                		return;
	 		                	case 1:
	 		                		showEditActivity(position);
		 		   	            	return;
 		                	}
 		                }
 		            });
 		            AlertDialog alert = builder.create();
					alert.show();
					currentTab=sportsmanTab;
				}
 		    }
 		});
    }
    
    private void setMacrocycleslist(){
    	listMacrocycles = (ListView) findViewById(R.id.listMacrocycles);
    	adapterMacrocycle = new ImageAdapterMacrocycle(this, manageMacrocycle.readAllMacrocycle());
    	listMacrocycles.setAdapter(adapterMacrocycle);
    	listMacrocycles.setOnItemClickListener(new OnItemClickListener() {
 		    public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
 		    	final Macrocycle itemMacrocycle = (Macrocycle) listMacrocycles.getAdapter().getItem(position);
 		    	if(itemMacrocycle != null) {
 		            AlertDialog.Builder builder = new AlertDialog.Builder(instance);
 		            builder.setTitle("Pick an Option");
 		            builder.setItems(popupItemsMacrocycle, new DialogInterface.OnClickListener() {
 		                public void onClick(DialogInterface dialog, int item) {
 		                	switch(item){
	 		                	case 0:
	 		                		manageMacrocycle.deleteMacrocycle(itemMacrocycle.getName());
	 		                		adapterMacrocycle = new ImageAdapterMacrocycle(instance, manageMacrocycle.readAllMacrocycle());
	 		                		listMacrocycles.setAdapter(adapterMacrocycle);
	 		                		return;
	 		                	case 1:
	 		                		showEditActivity(position);
		 		   	            	return;
	 		                	case 2:
	 		                		finish();
		 		               		Intent intent = new Intent(MainMenu.this, ListMicrocycles.class);
			 		               	Bundle b = new Bundle();
				 		       		b.putInt("key", position); //Your id
				 		       		intent.putExtras(b); //Put your id to your next Intent
		 		                   	startActivity(intent);
 		                	}
 		                }
 		            });
 		            AlertDialog alert = builder.create();
					alert.show();
				}
 		    	currentTab=macrocyclesTab;
 		    }
 		});
    	
    }
    
    private void setCompetitionList(){
 		listCompetition = (ListView) findViewById(R.id.listCompetitions);
 
 		adapterCompetition = new ImageAdapterCompetition(this, manageCompetition.readAllCompetitions());
 		listCompetition.setAdapter(adapterCompetition);
 		listCompetition.setOnItemClickListener(new OnItemClickListener() {
 		    public void onItemClick(AdapterView<?> a, View v, final int position, long id) {
 		    	final Competition itemCompetition = (Competition) listCompetition.getAdapter().getItem(position);
 		    	if(itemCompetition != null) {
 		            AlertDialog.Builder builder = new AlertDialog.Builder(instance);
 		            builder.setTitle("Pick an Option");
 		            builder.setItems(popupItemsCompetition, new DialogInterface.OnClickListener() {
 		                public void onClick(DialogInterface dialog, int item) {
 		                	switch(item){
	 		                	case 0:
	 		                		manageCompetition.deleteCompetition(itemCompetition.getNameCompetition());
	 		                		adapterCompetition = new ImageAdapterCompetition(instance, manageCompetition.readAllCompetitions());
	 		                		listCompetition.setAdapter(adapterCompetition);
	 		                		return;
	 		                	case 1:
	 		                		showEditActivity(position);
		 		   	            	return;
	 		                	case 2: 
	 		                		finish();
		 		               		Intent intent = new Intent(MainMenu.this, ChronometerActivity.class);
		 		                   	startActivity(intent);
 		                	}
 		                }
 		            });
 		            AlertDialog alert = builder.create();
					alert.show();
				}
 		    	currentTab=competitionTab;
 		    }
 		});
    }
    
    private void showEditActivity(int position){
    	finish();
 		Intent intent = new Intent(MainMenu.this, editClasses.get(currentTab));
		Bundle b = new Bundle();
		b.putInt("key", position); //Your id
		intent.putExtras(b); //Put your id to your next Intent
    	startActivity(intent);
    }
    
    
    
    @Override
    public void onBackPressed() {
    	manageSportsman.getSportsmanDAO().close();
    	manageMacrocycle.getMacrocycleDAO().close();
    	manageMicrocycle.getMicrocycleDAO().close();
    	manageCompetition.getCompetitionDAO().close();
    	finish();
	    return;
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_menu_options, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        currentTab = tabHost.getCurrentTab();
        switch (item.getItemId()) {
        case R.id.add_option:
            addItem();
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }    
    
	public void search() {
		
		search = (EditText) findViewById(R.id.fieldSearch);
		actualSearch = search.getText().toString();
		
		if(!actualSearch.equals("")){
			if(tabHost.getCurrentTab() == 0){
				adapterSportsman = new ImageAdapterSportsman(this, manageSportsman.searchSportman(actualSearch));
				listSportsman.setAdapter(adapterSportsman);					
			}
				
			else if(tabHost.getCurrentTab() == 1){
				adapterMacrocycle = new ImageAdapterMacrocycle(this, manageMacrocycle.searchMacrocycles(actualSearch));
			   	listMacrocycles.setAdapter(adapterMacrocycle);
			}
				
			else if(tabHost.getCurrentTab() == 2){
				adapterCompetition = new ImageAdapterCompetition(this, manageCompetition.searchCompetitions(actualSearch));
			    listCompetition.setAdapter(adapterCompetition);
			}			
		}
		
		else{
			if(tabHost.getCurrentTab() == 0){
				adapterSportsman = new ImageAdapterSportsman(this, manageSportsman.readAllSportsman());				
				listSportsman.setAdapter(adapterSportsman);					
			}
			
			else if(tabHost.getCurrentTab() == 1){
				adapterMacrocycle = new ImageAdapterMacrocycle(this, manageMacrocycle.readAllMacrocycle());
		    	listMacrocycles.setAdapter(adapterMacrocycle);
			}
			
			else if(tabHost.getCurrentTab() == 2){
				adapterCompetition = new ImageAdapterCompetition(this, manageCompetition.readAllCompetitions());				
				listCompetition.setAdapter(adapterCompetition);
			}	
		}
		
	}
    
    private void addItem(){
    	finish();
		Intent intent = new Intent(MainMenu.this, createClases.get(currentTab));
    	startActivity(intent);
    }
    
    public static void addDrawableSportsman(){
    	drawablesSportsman.add(res.getDrawable(R.drawable.icon_sportsman));    	
    }
    
    public static void addDrawableCompetitions(){
    	drawablesCompetitions.add(res.getDrawable(R.drawable.icon_sportsman));    	
    }
    
    
    public static void addDrawableMacrocycles(){
    	drawablesMacrocycles.add(res.getDrawable(R.drawable.icon_sportsman));    	
    }
    
    public static void addDrawableMicrocycles(){
    	drawablesMicrocycles.add(res.getDrawable(R.drawable.icon_sportsman));    	
    }
    private final int sportsmanTab=0,macrocyclesTab=1,competitionTab=2; 
	private final CharSequence[] popupItems = {"Delete", "Edit", "Cancel"};
	private final CharSequence[] popupItemsMacrocycle = {"Delete", "Edit", "Manage Microcycles", "Cancel"};
	private final CharSequence[] popupItemsCompetition = {"Delete", "Edit", "Start Chronometer", "Cancel"};
    public static MainMenu instance=null;
    public static ArrayList<Drawable> drawablesCompetitions = new ArrayList<Drawable>();
    public static ArrayList<Drawable> drawablesSportsman = new ArrayList<Drawable>();
    public static ArrayList<Drawable> drawablesMacrocycles = new ArrayList<Drawable>();
    public static ArrayList<Drawable> drawablesMicrocycles = new ArrayList<Drawable>();
    public static ListView listSportsman;
    public static ListView listCompetition;
    public static ListView listMacrocycles;
    public static ImageAdapterSportsman adapterSportsman;
    public static ImageAdapterCompetition adapterCompetition;
    public static ImageAdapterMacrocycle adapterMacrocycle;
    public static ManageCompetition manageCompetition;
    public static ManageSportsman manageSportsman;
    public static ManageMacrocycle manageMacrocycle;
    public static ManageMicrocycle manageMicrocycle;
    static Resources res;
    private static int currentTab;
    private ArrayList<Class> createClases = new ArrayList<Class>();
    private ArrayList<Class> editClasses = new ArrayList<Class>();
    private TextWatcher watcher;
    private TabHost tabHost;
    private EditText search;
	private String actualSearch;
	
}